package com.gmcloud.common.feign;

import com.alibaba.cloud.sentinel.feign.SentinelFeignAutoConfiguration;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
import com.gmcloud.common.feign.parser.GmHeaderRequestOriginParser;
import com.gmcloud.common.feign.sentinel.ext.GmSentinelFeign;
import com.gmcloud.common.feign.sentinel.handle.GmUrlBlockHandler;
import feign.Feign;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * @author zl.sir
 * @version 1.0
 * @since 2022/8/17 19:37
 * sentinel 配置
 */
@Configuration(proxyBeanMethods = false)
@AutoConfigureBefore(SentinelFeignAutoConfiguration.class)
public class GmFeignAutoConfiguration {


    /**
     * 支持自动降级注入 重写 {@link com.alibaba.cloud.sentinel.feign.SentinelFeign}
     * @return Feign.Builder
     */
    @Bean
    @Scope("prototype")
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "feign.sentinel.enabled")
    public Feign.Builder feignSentinelBuilder() {
        return GmSentinelFeign.builder();
    }

    /**
     * sentinel统一降级限流策略
     * @return BlockExceptionHandler
     */
    @Bean
    @ConditionalOnMissingBean
    public BlockExceptionHandler blockExceptionHandler() {
        return new GmUrlBlockHandler();
    }

    /**
     * sentinel 请求头解析判断
     * @return RequestOriginParser
     */
    @Bean
    @ConditionalOnMissingBean
    public RequestOriginParser requestOriginParser() {
        return new GmHeaderRequestOriginParser();
    }
}
